<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:deviceControl:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:deviceControl:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:deviceControl:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceControlList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属企业" align="center" prop="companyName" />
      <el-table-column label="图标" align="center" prop="icon" >
        <template slot-scope="scope">
          <el-image style="width: 40px; height: 40px" :src="getSensorIcon(scope.row.icon)" fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="所属系列" align="center" prop="typeName" />
      <el-table-column label="所属传感器" align="center" prop="seriesIoName" />
      <el-table-column label="排序号" align="center" prop="orderNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:deviceControl:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:deviceControl:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备控制批量对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="所属系列" prop="deviceTypeId">
          <el-select v-model="form.deviceTypeId" placeholder="请选择设备系列" :disabled="form.id!=null">
              <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属传感器" prop="seriesIoId">
          <el-select v-model="form.seriesIoId" placeholder="请选择所属传感器" :disabled="form.id!=null">
              <el-option v-for="item in seriesIoList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="值范围" prop="displayModel" v-if="form.displayModel === 'control_slider'">
          <el-input v-model="form.valueStart" placeholder="最小值" style="width:120px"/>&nbsp;&nbsp;&nbsp;~&nbsp;&nbsp;&nbsp;
          <el-input v-model="form.valueEnd" placeholder="最大值" style="width:120px" />
        </el-form-item>
        <el-form-item label="单选框选项" prop="displayModel" v-if="(form.displayModel === 'control_ratio' || form.displayModel === 'control_selector')">
          <div class="option-box">
            <el-table
              size="mini"
              :data="optionList"
              border
              style="width: 100%">
              <el-table-column label="序号" width="70" type="index" :index="indexMethod" align="center"></el-table-column>
              <el-table-column align="center"  label="变量名称">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.name" placeholder="请输入选项名" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="显示图标">
                <template slot-scope="scope">
                  <div style="width: 40px;height: 40px;cursor: pointer;margin-left: 10px;" v-show="scope.row.icon" @click="selectIcon(scope.$index)">
                    <img style="width: 100%;height: 100%;" :src="getSensorIcon(scope.row.icon)" alt="">
                  </div>
                  <el-button v-show="!scope.row.icon" style="background-color:#03c2c2;color:#fff" @click="selectIcon(scope.$index)" >选择</el-button>
                </template>
              </el-table-column>
              <el-table-column align="center" label="变量值">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.value" placeholder="请输入值" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="70" >
                <template slot-scope="scope">
                  <i class="el-icon-delete" style="cursor: pointer;" @click.stop="delOption(scope.$index,scope.row)" ></i>
                </template>
              </el-table-column>
            </el-table>
            <el-button class="add-btn" type="primary" icon="el-icon-plus" @click="addOption" >添加选项</el-button>
          </div>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" disabled/>
        </el-form-item>
        <el-form-item label="使用说明" prop="illustrate">
          <el-input v-model="form.illustrate" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="排序号" prop="orderNum">
          <el-input-number v-model="form.orderNum" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="显示图标" prop="icon">
          <div style="width: 40px;height: 40px;cursor: pointer;margin-left: 10px;" v-show="form.icon" @click="selectIcon(-1)">
            <img style="width: 100%;height: 100%;" :src="getSensorIcon(form.icon)" alt="">
          </div>
          <el-button v-show="!form.icon" style="background-color:#03c2c2;color:#fff" @click="selectIcon(-1)" >选择</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择图标" :visible.sync="iconPopup" width="800px" append-to-body>
      <div>
        <Icon :target="form.icon" @change="onIconChange"></Icon>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSelect" >确 定</el-button>
        <el-button @click="iconPopup=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeviceControl, getDeviceControl, delDeviceControl, addDeviceControl, updateDeviceControl } from "@/api/device/deviceControl";
import { deviceTypeOptions } from "@/api/device/deviceType";
import { seriesIoOptions , getSeriesIo } from "../../../api/device/seriesIo";
import Icon from '@/components/Icons/index.vue'
export default {
  name: "DeviceControl",
  components:{Icon},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      iconPopup:false,
      targetIcon:'',
      // 总条数
      total: 0,
      // 设备控制批量表格数据
      deviceControlList: [],
      deviceTypeList:[],
      seriesIoList:[],
      optionList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        name: null,
        icon: null,
        seriesIoId: null,
        flagValue: null,
        minValue: null,
        maxValue: null,
        displayModel: null,
        illustrate: null,
        orderNum: null,
        unit:null
      },
      // 表单参数
      form: {},
      optIndex:-1,
      // 表单校验
      rules: {
        companyId: [
          { required: true, message: "所属企业不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        seriesIoId: [
          { required: true, message: "传感器模板Id不能为空", trigger: "blur" }
        ],
        displayModel: [
          { required: true, message: "显示方式不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "排序号不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.queryParams.companyId = this.$route.query.companyId;
    this.getList();
    this.getDeviceTypeOptions();
  },
  watch:{
    "form.deviceTypeId"(val){
      if(val!==null) this.getSeriesIoOptions(val)
    },
    "form.seriesIoId"(val){
      if(val!==null && !this.form.id) this.getSeriesIoDetail(val)
    }
  },
  methods: {
    /** 查询设备控制批量列表 */
    getList() {
      this.loading = true;
      listDeviceControl(this.queryParams).then(response => {
        this.deviceControlList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //设备类型下拉
    getDeviceTypeOptions(){
        deviceTypeOptions().then(res => this.deviceTypeList = res.data)
    },
    //设备类型下拉
    getSeriesIoOptions(deviceTypeId){
        seriesIoOptions({control:'1',"deviceTypeId":deviceTypeId}).then(res => this.seriesIoList = res.data)
    },

    //获取传感器详情
    getSeriesIoDetail(seriesIoId){
        getSeriesIo(seriesIoId).then( res => {
          this.form.displayModel = res.data.displayModel;
          this.form.minValue = res.data.minValue;
          this.form.maxValue = res.data.maxValue;
          this.form.illustrate = res.data.illustrate;
          this.form.unit = res.data.unit;
          this.form.icon = res.data.icon;
          if(res.data.commandList) this.optionList = res.data.commandList.map( o => {o.id = null; o.icon = '' ; return o;})
        })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.optionList = [];
      this.form = {
        id: null,
        companyId: this.queryParams.companyId,
        deviceTypeId:null,
        name: null,
        icon: null,
        seriesIoId: null,
        flagValue: null,
        minValue: null,
        maxValue: null,
        displayModel: null,
        illustrate: null,
        orderNum: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备控制批量";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDeviceControl(id).then(response => {
        this.form = response.data;
        if(response.data.commandList) this.optionList = response.data.commandList
        this.open = true;
        this.title = "修改设备控制批量";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.optionList) this.form.commandList = this.optionList
          debugger
          if (this.form.id != null) {
            updateDeviceControl(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeviceControl(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备控制批量编号为"' + ids + '"的数据项？').then(function() {
        return delDeviceControl(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    selectIcon(optIndex){
      if(optIndex != -1){
        this.optIndex = optIndex ;
        this.targetIcon = this.optionList[optIndex].icon;
      }else{
        this.optIndex = -1;
        this.targetIcon = this.form.icon;
        this.optForm = null;
      }
      this.iconPopup = true;
    },
    onIconChange(value){
      this.targetIcon = value;
    },
    handleSelect(){
      if(this.targetIcon && this.optIndex != -1){
        this.optionList[this.optIndex].icon = this.targetIcon;
        this.iconPopup = false;
      }else if(this.targetIcon){
        this.form.icon = this.targetIcon;
        this.iconPopup = false;
      }
    },
    indexMethod(index){
      return '选项'+(index+1)
    },
    addOption(){
      this.optionList.push({
        id:null,
        name:'',
        value:'',
        icon:''
      })
      this.$nextTick()
    },
    delOption(index,row){
      this.optionList.splice(index,1)
    },
  }
};
</script>
